package com.github.andy0106.kersstjtl.api;

import com.github.andy0106.kersstjtl.files.File;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;

public class ApiBuffer extends ApiRequest {
    public static final Gson gson = new Gson();
    private static ArrayList<Package> packages_bf = new ArrayList<>();
    private static ArrayList<String> packages_name_bf = new ArrayList<>();
    private static PackagesCache packages_cache;
    public static String CACHE_DIR = "";
    private static boolean first = true;

    public static ArrayList<Package> getAllPackages() {
        return packages_bf;
    }

    public static ArrayList<String> getAllPackagesName() {
        return packages_name_bf;
    }

    public static ArrayList<Package> getPackagesByName(String packname) {
        ArrayList<Package> packages = new ArrayList<>();
        packages_bf.forEach(pack -> {
            if (pack.getName().equals(packname)) packages.add(pack);
        });
        return packages;
    }

    public static Package getLatestPackageByName(String name) {
        return packages_cache.packages.get(name);
    }

    public static String getLatestPackageJsonByName(String name) {
        return gson.toJson(packages_cache.packages.get(name), Package.class);
    }

    public static boolean get() {
        long now = ApiRequest.getTimestamp();
        if (first) {
            packages_bf = ApiRequest.get_all_packages();
            packages_name_bf = ApiRequest.get_all_packages_name();
            first = false;
        }
        if (packages_cache.timestamp == now) return true;
        _get();
        packages_cache.timestamp = now;
        return true;
    }
    
    private static void _get() {
        packages_name_bf.forEach(name -> {
            packages_bf = ApiRequest.get_all_packages();
            packages_name_bf = ApiRequest.get_all_packages_name();
            ArrayList<Package> packages = getPackagesByName(name);
            Package latest_pack = packages.get(0);
            latest_pack.loadPackage();
            packages_cache.packages.put(latest_pack.getName(), latest_pack);
        });
    }

    public static void save() {
        new File("packagescache.json", CACHE_DIR).writeString_UTF_8(gson.toJson(packages_cache, PackagesCache.class));
    }

    public static void load() {
        packages_cache = gson.fromJson(new File("packagescache.json", CACHE_DIR).readString_UTF_8(), PackagesCache.class);
        if (packages_cache == null) {
            packages_cache = new PackagesCache();
        }
    }
}

